import React, { useEffect, useMemo, useRef } from 'react';
import { usePlatform } from '@/common/hooks';
import { enumLiveTypeTextToId } from '@/common/enum';
import LivePlayer from '@/components/LivePlayer';

import styles from '../style/Player.scss';

const Player = ({ data }) => {
  const playerRef = useRef();
  const liveTypeId = enumLiveTypeTextToId[data.liveType];
  const { isIos } = usePlatform();
  const urls = useMemo(() => {
    const { liveUrl } = data;
    // ios端替换为m3u8播放
    const playUrl = isIos ? liveUrl.replace(/\.flv$|\.flv(\?)/i, '.m3u8$1') : liveUrl;
    const protocolType = /m3u8/i.test(playUrl) ? 'm3u8' : 'flv';
    const playAddr = [{
      name: '标清',
      playUrl,
      protocolType,
    }];
    // const { playAddr, playAddr2 } = data;
    // if (playAddr2?.length) return playAddr2;

    return playAddr || [];
  }, [data]);

  useEffect(() => {
    playerRef.current?.create();
  }, [urls]);

  return (
    <div className={styles.container}>
      <div className={styles.wrapper}>
        <LivePlayer
          ref={playerRef}
          data={urls}
        >
          <LivePlayer.StatusRecommend
            sportId={liveTypeId}
            roomId={data.roomId}
            status={data.liveStatus}
            title={data.liveTitle}
            offLineTime={data.lastStartTime}
            userImage={data.headerImg}
            leagueName={data.matchName}
          />
        </LivePlayer>
      </div>
    </div>
  );
};

Player.defaultProps = {
  data: {},
};

export default Player;
